package com.itmuch.usercenter.controller.user;

import com.itmuch.usercenter.auth.CheckLogin;
import com.itmuch.usercenter.dao.user.UserMapper;
import com.itmuch.usercenter.domain.dto.user.JwtTokenRespDTO;
import com.itmuch.usercenter.domain.dto.user.LoginRespDTO;
import com.itmuch.usercenter.domain.dto.user.UserLoginDTO;
import com.itmuch.usercenter.domain.dto.user.UserRespDTO;
import com.itmuch.usercenter.domain.entity.user.User;
import com.itmuch.usercenter.service.user.UserService;
import com.itmuch.usercenter.utils.JwtOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private JwtOperator jwtOperator;


    @GetMapping("/{id}")
    @CheckLogin
    public User findById(@PathVariable Integer id){
    return userService.findById(id);
   }

   @GetMapping("/get/token")
   public String getToken(){
        Map<String,Object> map = new HashMap<>();
        map.put("id",1);
        map.put("wxNickname","andrew");
        map.put("role","admin");
        return jwtOperator.generateToken(map);
   }

   @PostMapping("/login/{openId}")
    public LoginRespDTO login(@RequestBody UserLoginDTO userLoginDTO,@PathVariable("openId") String openId){

       User user = userService.login(userLoginDTO, openId);
       Map<String,Object> map = new HashMap<>(3);
       map.put("id",user.getId());
       map.put("wxNickname",user.getWxNickname());
       map.put("role",user.getRoles());
       String token = jwtOperator.generateToken(map);
       log.info("用户{}登录成功,生成的token={},有效期到:{}",user.getWxNickname()
               ,token,jwtOperator.getExpirationDateFromToken(token)
       );
       return LoginRespDTO.builder()
               .userRespDTO(
                       UserRespDTO.builder()
                       .id(user.getId())
                       .avatarUrl(user.getAvatarUrl())
                       .bonus(user.getBonus())
                       .wxNickname(user.getWxNickname())
                       .build()
               )
               .jwtTokenRespDTO(
                       JwtTokenRespDTO.builder()
                               .expirationTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(jwtOperator.getExpirationDateFromToken(token)))
                               .token(token)
                               .build()
               ).build();
   }
}
